package com.google.code.sip.ucenter.imports;

import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.code.sip.ucenter.dao.CreditTypeDao;
import com.google.code.sip.ucenter.dao.mongo.CreditRuleDaoImpl;
import com.google.code.sip.ucenter.model.CreditRule;
import com.google.code.sip.ucenter.model.CreditRuleAmount;
import com.google.code.sip.ucenter.model.CreditType;

@Service("creditRuleImporter")
public class CreditRuleImporter extends AbstractImporter<CreditRule> {
	@Autowired
	private CreditRuleDaoImpl creditRuleDao;
	@Autowired
	private CreditTypeDao creditTypeDao;

	@Override
	protected CreditRule toEntity(Map<String, String> props) {
		CreditRule creditRule = new CreditRule();
		for (Map.Entry<String, String> entry : props.entrySet()) {
			String name = entry.getKey();
			String value = entry.getValue();
			if (name.startsWith("creditRuleAmount.")) {
				String creditTypeName = name.split("\\.")[1];
				CreditType creditType = creditTypeDao.getByName(creditTypeName);
				if (creditType != null) {
					CreditRuleAmount creditRuleAmount = new CreditRuleAmount();
					creditRuleAmount.setCreditType(creditType);
					creditRuleAmount.setAmout(Integer.parseInt(value));
					creditRule.getCreditRuleAmounts().add(creditRuleAmount);
				}
			} else {
				try {
					if (entityClass.getDeclaredField(name) != null) {
						beanUtilsBean.copyProperty(creditRule, name, value);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return creditRule;
	}

	@Override
	protected void doSave(CreditRule creditRule) {
		creditRuleDao.save(creditRule);
	}

	@Override
	protected void doInit() {
		creditRuleDao.clear();
	}

}
